package com.ad.aidai.fragments.order;

import android.animation.ObjectAnimator;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ad.aidai.R;
import com.ad.aidai.base.BaseFragment;
import com.ad.aidai.common.ADApp;
import com.ad.aidai.common.ADFragmentManager;
import com.ad.aidai.common.RxBus;
import com.ad.aidai.common.utils.CheckUtil;
import com.ad.aidai.common.utils.MultiStylesTextViewUtil;
import com.ad.aidai.common.widgets.NavigationTabStrip;
import com.ad.aidai.common.widgets.colorpop.FragmentInformer;
import com.ad.aidai.events.CommonEvent;
import com.ad.aidai.fragments.bind_school.BindSchoolFragment;
import com.ad.aidai.fragments.create_order.CreateOrderFragment;
import com.ad.aidai.fragments.order.order_allschool.OrderAllSchoolFragment;
import com.ad.aidai.fragments.order.order_nearby.OrderNearbyFragment;
import com.ad.aidai.fragments.order.order_push.OrderPushFragment;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * 主页fragment
 * <p>
 * Created by pure on 2016/12/8.
 */

public class OrderFragment extends BaseFragment {

    @BindView(R.id.nts_top)
    NavigationTabStrip ntsTop;
    @BindView(R.id.vp_content)
    ViewPager vpContent;
    @BindView(R.id.fab_create_order)
    ImageView fabFillOrder;
    @BindView(R.id.tv_go_bind_school)
    TextView tvGoBindSchool;
    @BindView(R.id.ll_no_bind_school)
    LinearLayout llNoBindSchool;


    private List<FragmentInfo> fragments;

    private boolean hasMeasured = false;
    private float vpConY;
    private float vpConH;
    private float fabY = 0;

    private float startY;
    private VelocityTracker mVelTracker;

    private CreateOrderFragment createOrderFragment;
    private FragmentViewPagerAdapter viewPagerAdapter;

    private boolean clickFabBtn = false;

    @Override
    protected void initLayout(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_order, container, false);
    }

    @Override
    protected void initView() {
        viewPagerAdapter = new FragmentViewPagerAdapter(getChildFragmentManager());
        viewPagerAdapter.setData(fragments);
        vpContent.setAdapter(viewPagerAdapter);
        vpContent.setOffscreenPageLimit(fragments.size() - 1);
        ntsTop.setViewPager(vpContent, 0);
    }

    @Override
    protected void initData() {
        fragments = new ArrayList<>();

        if (ADApp.getUser().getSchoolId() != null) {
            llNoBindSchool.setVisibility(View.GONE);
            initFragment();
        } else {
            new MultiStylesTextViewUtil(getContext())
                    .initTextView(tvGoBindSchool)
                    .appendColorText("未绑定学校!\n爱代服务需要先绑定学校信息\n前往", R.color.black)
                    .appendColorText("绑定", R.color.white, new MultiStylesTextViewUtil.OnTextClickListener() {
                        @Override
                        public void textClick(View v, String text) {
                            getActivity()
                                    .getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.fragment_slide_left_enter, 0, 0, R.anim
                                            .fragment_slide_left_exit)
                                    .add(android.R.id.content, new BindSchoolFragment(), "bindSchool")
                                    .addToBackStack("bindSchool")
                                    .commit();
                        }
                    })
                    .create();
        }

        getWidgetWidthHeight();
    }

    private void initFragment() {
        fragments.add(new FragmentInfo(OrderNearbyFragment.class, null));
        fragments.add(new FragmentInfo(OrderAllSchoolFragment.class, null));
        fragments.add(new FragmentInfo(OrderPushFragment.class, null));
    }

    @OnClick(R.id.fab_create_order)
    public void onClick(View view) {
        if (CheckUtil.checkStrNull(ADApp.getUser().getUserPayNum())) {
            toast("请先到个人资料页面填写支付宝账号");
            return;
        }
        createOrderFragment = new CreateOrderFragment();
        if(this.getClass().getSimpleName().equals(ADFragmentManager.getTopTag()) || clickFabBtn) {
            clickFabBtn = false;
            return;
        }
        clickFabBtn = true;
        FragmentInformer informer = new FragmentInformer(getContext());
        informer.setCircleColor(ContextCompat.getColor(getActivity(), R.color.colorTheme));
        informer.setPageColor(Color.WHITE);
        informer.setBaseView(view, FragmentInformer.MODE_CENTER, false);
        informer.informColorPopPageFragment(createOrderFragment);
        FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
        transaction.setCustomAnimations(0, R.anim.popup_exit, 0, R.anim.fragment_slide_left_exit);
        transaction.addToBackStack(null);
        transaction.add(android.R.id.content, createOrderFragment);
        transaction.commit();
    }

    /**
     * 获取控件的宽高等参数
     */
    private void getWidgetWidthHeight() {
        ViewTreeObserver vto = fabFillOrder.getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                if (!hasMeasured) {
                    vpConY = vpContent.getY();
                    vpConH = vpContent.getHeight();
                    //获取到宽度和高度后，可用于计算
                    hasMeasured = true;
                }
                return true;
            }
        });
    }

    /**
     * 显示和隐藏浮动按钮
     *
     * @param showable 是否显示
     */
    private void showFab(boolean showable) {
        if(fabY == 0) {
            fabY = fabFillOrder.getY();
        }
        ObjectAnimator anim = ObjectAnimator.ofFloat(fabFillOrder, "y", fabFillOrder.getY(), showable ? fabY : vpConY
                + vpConH);
        anim.setDuration(500);
        anim.start();
    }

    @Override
    protected void subscribeEvents() {
        //订阅事件,显示和隐藏浮动按钮
        addSubscription(RxBus.getInstance()
                .toObservable()
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Action1<Object>() {
                    @Override
                    public void call(Object o) {
                        if (o instanceof CommonEvent) {
                            CommonEvent event = (CommonEvent) o;
                            switch (event.getEvent()) {
                                case CommonEvent.ON_TOUCH_ORDERFRAGMENT:
                                    MotionEvent motionEvent = (MotionEvent) event.getData();
                                    if (motionEvent == null) {
                                        Logger.t(this.getClass().getSimpleName()).e("motionEvent : null");
                                    } else {
                                        dealEvent(motionEvent);
                                    }
                                    break;
                                case CommonEvent.IS_EXIT_CREATE_ORDER:
                                    createOrderFragment = null;
                                    break;
                                case CommonEvent.SCHOOL_INFO_BIND:
                                    llNoBindSchool.setVisibility(View.GONE);
                                    initFragment();
                                    vpContent.setAdapter(viewPagerAdapter);
                                    vpContent.setOffscreenPageLimit(fragments.size() - 1);
                                    ntsTop.setViewPager(vpContent, 0);
                                    break;
                            }
                        }
                    }
                })
                .subscribe(RxBus.defaultSubscriber()));
    }

    private void dealEvent(MotionEvent event) {
        getVelocityTracker(event);

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startY = event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:

                mVelTracker.computeCurrentVelocity(10);
                //获取x方向上的速度
                float velocityY = mVelTracker.getYVelocity(0);

                if (Math.abs(velocityY) >= 0f) {
                    if (event.getRawY() - startY > 0f) {
                        showFab(true);
                    } else {
                        showFab(false);
                    }
                }

                recycleVelocityTracker();
                break;
        }
    }

    /**
     * 获取速度追踪器
     *
     * @return
     */
    private VelocityTracker getVelocityTracker(MotionEvent event) {
        if (mVelTracker == null) {
            mVelTracker = VelocityTracker.obtain();
        }
        mVelTracker.addMovement(event);
        return mVelTracker;
    }

    /**
     * 回收速度追踪器
     */
    private void recycleVelocityTracker() {
        if (mVelTracker != null) {
            mVelTracker.clear();
            mVelTracker.recycle();
            mVelTracker = null;
        }
    }

    class FragmentInfo {
        private Class<?> clss;
        private Bundle args;
        private BaseFragment fragment;

        FragmentInfo(Class<?> _class, Bundle _args) {
            clss = _class;
            args = _args;
        }
    }

    class FragmentViewPagerAdapter extends FragmentStatePagerAdapter {

        List<FragmentInfo> fragmentInfos;

        FragmentViewPagerAdapter(FragmentManager fm) {
            super(fm);
            fragmentInfos = new ArrayList<>();
        }

        public void setData(List<FragmentInfo> fragmentInfos) {
            this.fragmentInfos = fragmentInfos;
        }

        @Override
        public Fragment getItem(int position) {
            FragmentInfo fragmentInfo = fragmentInfos.get(position);
            if (fragmentInfo.fragment == null) {
                fragmentInfo.fragment = (BaseFragment) Fragment.instantiate(getContext(), fragmentInfo.clss.getName(),
                        fragmentInfo.args);
            }
            return fragmentInfo.fragment;
        }


        @Override
        public int getCount() {
            return fragmentInfos.size();
        }
    }

    @Override
    public boolean onActivityBackPressed() {
        return true;
    }
}
